<!DOCTYPE html>
<html>

<head>
    <title>JSON响应测试</title>
</head>

<body>
    <h1>JSON响应测试</h1>

    <h3>GET请求测试</h3>
    <button onclick="testGet()">测试GET请求</button>

    <h3>POST请求测试</h3>
    <form id="jsonForm">
        <label>用户ID: <input type="number" id="userId" value="123"></label><br>
        <label>JSON数据: <textarea id="jsonData">{"name": "测试用户", "age": 25}</textarea></label><br>
        <button type="submit">发送POST请求</button>
    </form>

    <div id="result"></div>

    <script>
        // GET请求测试
        async function testGet() {
            const userId = document.getElementById('userId').value;
            try {
                const response = await fetch(`/users/${userId}`, {
                    method: 'GET'
                });

                // 检查响应状态
                if (!response.ok) {
                    const errorText = await response.text();
                    document.getElementById('result').textContent = `GET请求失败:\n状态码: ${response.status}\n错误信息: ${errorText}`;
                    return;
                }

                const result = await response.json();
                document.getElementById('result').textContent = 'GET请求结果:\n' + JSON.stringify(result, null, 2);
            } catch (error) {
                document.getElementById('result').textContent = 'GET请求错误: ' + error.message;
            }
        }

        // POST请求测试
        document.getElementById('jsonForm').onsubmit = async function (e) {
            e.preventDefault();
            const userId = document.getElementById('userId').value;
            const jsonData = document.getElementById('jsonData').value;

            try {
                const response = await fetch(`/users/${userId}`, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: jsonData
                });

                // 检查响应状态
                if (!response.ok) {
                    const errorText = await response.text();
                    document.getElementById('result').textContent = `POST请求失败:\n状态码: ${response.status}\n错误信息: ${errorText}`;
                    return;
                }

                const result = await response.json();
                document.getElementById('result').textContent = 'POST请求结果:\n' + JSON.stringify(result, null, 2);
            } catch (error) {
                document.getElementById('result').textContent = 'POST请求错误: ' + error.message;
            }
        };
    </script>
</body>

</html>